/**
 * Moments (Friends Circle) Module - Handles social feed functionality
 */

// DOM Elements
let socialFeed;
let createPostBtn;
let postModal;
let postContent;
let mediaPreview;
let uploadImage;
let uploadVideo;
let locationBtn;
let postTop;
let publishBtn;
let closePostModalBtn;
let commentModal;
let commentText;
let submitCommentBtn;
let closeCommentModalBtn;

// State variables
let currentPage = 0;
let totalPages = 1;
let loading = false;
let currentMomentId = null; // For commenting
let moments = [];
let pendingMediaUploads = [];

// Initialize the moments module
document.addEventListener('DOMContentLoaded', function() {
    // Get DOM elements
    socialFeed = document.getElementById('social-feed');
    createPostBtn = document.getElementById('create-post-btn');
    postModal = document.getElementById('post-modal');
    postContent = document.getElementById('post-content');
    mediaPreview = document.getElementById('media-preview');
    uploadImage = document.getElementById('upload-image');
    uploadVideo = document.getElementById('upload-video');
    locationBtn = document.getElementById('location-btn');
    postTop = document.getElementById('post-top');
    publishBtn = document.getElementById('publish-post');
    closePostModalBtn = document.getElementById('close-post-modal');
    commentModal = document.getElementById('comment-modal');
    commentText = document.getElementById('comment-text');
    submitCommentBtn = document.getElementById('submit-comment');
    closeCommentModalBtn = document.getElementById('close-comment-modal');
    
    // Add event listeners
    createPostBtn?.addEventListener('click', openPostModal);
    closePostModalBtn?.addEventListener('click', closePostModal);
    publishBtn?.addEventListener('click', publishPost);
    closeCommentModalBtn?.addEventListener('click', closeCommentModal);
    submitCommentBtn?.addEventListener('click', submitComment);
        
    // Media upload event listeners
    uploadImage?.addEventListener('change', handleImageUpload);
    uploadVideo?.addEventListener('change', handleVideoUpload);
        
    // Scroll event listener for infinite scroll
    document.getElementById('friends')?.addEventListener('scroll', handleScroll);

    // Set up WebSocket handlers
    setupWebSocketHandlers();

    // Load initial moments data
    loadMoments();
});
        
// Setup WebSocket handlers
function setupWebSocketHandlers() {
    if (!window.wsManager) {
        console.error('WebSocket manager not available');
        return;
    }

    // Handle moment-related events
    window.wsManager.on('moment', 'MOMENTS_DATA', handleMomentsData);
    window.wsManager.on('moment', 'MOMENT_CREATED', handleMomentCreated);
    window.wsManager.on('moment', 'MOMENT_LIKE_UPDATED', handleMomentLikeUpdated);
    window.wsManager.on('moment', 'MOMENT_COMMENTED', handleMomentCommented);
    window.wsManager.on('moment', 'MOMENT_DELETED', handleMomentDeleted);
    window.wsManager.on('moment', 'COMMENT_DELETED', handleCommentDeleted);
    window.wsManager.on('moment', 'MEDIA_UPLOAD_SUCCESS', handleMediaUploadSuccess);
    window.wsManager.on('moment', 'MEDIA_UPLOADS_FINALIZED', handleMediaUploadsFinalized);
    window.wsManager.on('moment', 'ERROR', handleError);
}

// Handle moments data received from server
function handleMomentsData(data) {
    console.log('Received moments data:', data);
    
    if (!data.success || !data.moments) {
        showError('Failed to load moments');
        return;
    }
    
    // If it's the first page, replace all moments
    if (currentPage === 0 || data.currentPage === 0) {
        moments = data.moments;
    } else {
        // Otherwise append to existing moments
        moments = moments.concat(data.moments);
                }
    
    // Update pagination info
    currentPage = data.currentPage;
    totalPages = data.totalPages;
    
    // Render moments
    renderMoments();
    
    // Hide loading spinner
    hideLoading();
}

// Handle new moment creation
function handleMomentCreated(data) {
    console.log('Moment created:', data);
    
    if (!data.success || !data.moment) {
        showError('Failed to create moment');
        return;
    }
    
    // Add new moment to the beginning of the array
    moments.unshift(data.moment);
        
    // Re-render moments
    renderMoments();
    
    // Close post modal
                closePostModal();
    
    // Clear pending media uploads
    pendingMediaUploads = [];
}

// Handle moment like update
function handleMomentLikeUpdated(data) {
    console.log('Moment like updated:', data);
    
    if (!data.success || !data.moment) {
        showError('Failed to update like');
        return;
    }
    
    // Update the moment in the array
    const index = moments.findIndex(m => m.id === data.moment.id);
    if (index !== -1) {
        moments[index] = data.moment;
        
        // Update only the specific moment element
        updateMomentElement(data.moment);
            }
}

// Handle moment comment
function handleMomentCommented(data) {
    console.log('Moment commented:', data);
    
    if (!data.success || !data.moment) {
        showError('Failed to add comment');
        return;
    }
    
    // Update the moment in the array
    const index = moments.findIndex(m => m.id === data.moment.id);
    if (index !== -1) {
        moments[index] = data.moment;
        
        // Update only the specific moment element
        updateMomentElement(data.moment);
    }
    
    // Close comment modal
                closeCommentModal();
            }
    
// Handle moment deletion
function handleMomentDeleted(data) {
    console.log('Moment deleted:', data);
    
    if (!data.success || !data.momentId) {
        showError('Failed to delete moment');
        return;
    }
    
    // Remove the moment from the array
    moments = moments.filter(m => m.id !== data.momentId);
    
    // Remove the moment element from the DOM
    const momentElement = document.querySelector(`.moment-item[data-moment-id="${data.momentId}"]`);
    if (momentElement) {
        momentElement.remove();
    }
}

// Handle comment deletion
function handleCommentDeleted(data) {
    console.log('Comment deleted:', data);
    
    if (!data.success || !data.commentId) {
        showError('Failed to delete comment');
        return;
    }
    
    // Find the moment that contains this comment
    const momentWithComment = moments.find(m => 
        m.comments && m.comments.some(c => c.id === data.commentId)
    );
    
    if (momentWithComment) {
        // Update the moment's comments
        const momentIndex = moments.findIndex(m => m.id === momentWithComment.id);
        if (momentIndex !== -1) {
            moments[momentIndex].comments = moments[momentIndex].comments.filter(c => c.id !== data.commentId);
            
            // Update the moment element
            updateMomentElement(moments[momentIndex]);
        }
    }
}

// Handle media upload success
function handleMediaUploadSuccess(data) {
    console.log('Media upload success:', data);
    
    if (!data.success || !data.url) {
        showError('Failed to upload media');
        return;
    }
    
    // Add the URL to pending media uploads
    pendingMediaUploads.push(data.url);
    
    // Show the media in the preview
    addMediaToPreview(data.url);
}

// Handle media uploads finalized
function handleMediaUploadsFinalized(data) {
    console.log('Media uploads finalized:', data);
    
    if (!data.success) {
        showError('Failed to finalize media uploads');
        return;
    }
    
    // Update pending media uploads with the server's list
    pendingMediaUploads = data.mediaUrls || [];
}

// Handle WebSocket errors
function handleError(data) {
    console.error('WebSocket error:', data);
    showError(data.message || 'An error occurred');
}

// Load moments from server
function loadMoments(page = 0) {
    if (loading) return;
    
    loading = true;
    showLoading();
    
    // Get moments via WebSocket
    if (window.wsManager && window.wsManager.isMomentConnected) {
        window.wsManager.loadMoments(page);
        currentPage = page;
    } else {
        console.error('Moment WebSocket not connected');
        hideLoading();
        showError('Failed to connect to server');
        loading = false;
    }
    }
    
// Render moments in the feed
function renderMoments() {
    if (!socialFeed) return;
    
    // Clear loading indicator
        socialFeed.innerHTML = '';
        
    if (moments.length === 0) {
            socialFeed.innerHTML = `
                <div class="empty-state">
                    <i class="fas fa-users"></i>
                <p>No moments to display. Share something with your friends!</p>
                </div>
            `;
            return;
        }
        
    // Render each moment
    moments.forEach(moment => {
        const momentElement = createMomentElement(moment);
        socialFeed.appendChild(momentElement);
    });
}

// Create a moment element
function createMomentElement(moment) {
    const momentElement = document.createElement('div');
    momentElement.className = 'moment-item';
    momentElement.dataset.momentId = moment.id;
    
    // Get current user to check if moment belongs to user
    const userData = JSON.parse(sessionStorage.getItem('user'));
    const isCurrentUserMoment = userData && moment.userId.toString() === userData.id.toString();
    
    // Format the timestamp
    const momentDate = new Date(moment.createdAt);
    const formattedDate = formatMomentDate(momentDate);
    
    // Prepare media HTML
    let mediaHtml = '';
    if (moment.media && moment.media.length > 0) {
        if (moment.media.length === 1) {
            // Single image
            mediaHtml = `
                <div class="moment-media single-media">
                    <img src="${moment.media[0].mediaUrl}" alt="Moment image" class="moment-image">
                </div>
            `;
        } else {
            // Multiple images
            mediaHtml = `
                <div class="moment-media multiple-media">
                    ${moment.media.map(media => `
                        <div class="media-item">
                            <img src="${media.mediaUrl}" alt="Moment image" class="moment-image">
                        </div>
                    `).join('')}
                    </div>
                `;
            }
    }
    
    // Prepare comments HTML
    let commentsHtml = '';
    if (moment.comments && moment.comments.length > 0) {
        commentsHtml = `
            <div class="moment-comments">
                ${moment.comments.map(comment => `
                    <div class="moment-comment" data-comment-id="${comment.id}">
                        <div class="comment-user">
                            <img src="${comment.userAvatarUrl || '/images/avatar.png'}" alt="${comment.username}" class="comment-avatar">
                            <span class="comment-username">${comment.username}</span>
                        </div>
                        <p class="comment-content">${escapeHtml(comment.content)}</p>
                        ${comment.userId.toString() === (userData ? userData.id.toString() : '') ? 
                            `<button class="delete-comment-btn" data-comment-id="${comment.id}">
                                <i class="fas fa-trash-alt"></i>
                            </button>` : ''}
                    </div>
                `).join('')}
            </div>
        `;
    }
    
    // Construct the moment HTML
    momentElement.innerHTML = `
        <div class="moment-header">
            <div class="moment-user">
                <img src="${moment.userAvatarUrl || '/images/avatar.png'}" alt="${moment.username}" class="moment-avatar">
                <div class="user-info">
                    <h4>${moment.username}</h4>
                    <span class="moment-time">${formattedDate}</span>
                            </div>
                        </div>
            ${isCurrentUserMoment ? `
                <div class="moment-actions">
                    <button class="delete-moment-btn" data-moment-id="${moment.id}">
                        <i class="fas fa-trash-alt"></i>
                    </button>
                    </div>
                    ` : ''}
                </div>
        <div class="moment-content">
            <p>${formatMomentContent(moment.content)}</p>
                </div>
                ${mediaHtml}
        <div class="moment-stats">
            <div class="moment-stat">
                <button class="like-btn ${moment.liked ? 'active' : ''}" data-moment-id="${moment.id}">
                    <i class="fas fa-heart"></i>
                    <span>${moment.likeCount || 0}</span>
                </button>
                    </div>
            <div class="moment-stat">
                <button class="comment-btn" data-moment-id="${moment.id}">
                    <i class="fas fa-comment"></i>
                    <span>${moment.commentCount || 0}</span>
                </button>
                    </div>
                </div>
                ${commentsHtml}
    `;
    
    // Add event listeners to the moment element
    addMomentEventListeners(momentElement);
    
    return momentElement;
}

// Add event listeners to moment element
function addMomentEventListeners(momentElement) {
    // Like button
    const likeBtn = momentElement.querySelector('.like-btn');
    if (likeBtn) {
        likeBtn.addEventListener('click', function() {
            const momentId = parseInt(this.dataset.momentId);
            toggleLikeMoment(momentId);
                });
            }
    
    // Comment button
    const commentBtn = momentElement.querySelector('.comment-btn');
    if (commentBtn) {
        commentBtn.addEventListener('click', function() {
            const momentId = parseInt(this.dataset.momentId);
            openCommentModal(momentId);
            });
    }
        
    // Delete moment button
    const deleteBtn = momentElement.querySelector('.delete-moment-btn');
    if (deleteBtn) {
        deleteBtn.addEventListener('click', function() {
            const momentId = parseInt(this.dataset.momentId);
            confirmDeleteMoment(momentId);
            });
    }
        
    // Delete comment buttons
    const deleteCommentBtns = momentElement.querySelectorAll('.delete-comment-btn');
    deleteCommentBtns.forEach(btn => {
            btn.addEventListener('click', function(e) {
                e.stopPropagation();
                const commentId = parseInt(this.dataset.commentId);
            confirmDeleteComment(commentId);
            });
        });
    }
    
// Update a specific moment element
function updateMomentElement(moment) {
    const momentElement = document.querySelector(`.moment-item[data-moment-id="${moment.id}"]`);
    if (!momentElement) return;
    
    // Replace the existing element with new one
    const newMomentElement = createMomentElement(moment);
    momentElement.replaceWith(newMomentElement);
    }
    
// Toggle like on a moment
function toggleLikeMoment(momentId) {
    if (!window.wsManager || !window.wsManager.isMomentConnected) {
        showError('Not connected to server');
        return;
    }
    
    // Send like/unlike request via WebSocket
    window.wsManager.toggleLikeMoment(momentId);
    }
    
// Open the comment modal
function openCommentModal(momentId) {
    if (!commentModal || !commentText) return;
    
    // Set current moment ID for commenting
    currentMomentId = momentId;
    
    // Clear previous comment text
        commentText.value = '';
        
    // Show the modal
    commentModal.style.display = 'flex';
    
    // Focus on the comment textarea
            commentText.focus();
    }
    
// Close the comment modal
    function closeCommentModal() {
    if (!commentModal) return;
    
        commentModal.style.display = 'none';
    currentMomentId = null;
    }
    
// Submit a comment
function submitComment() {
    if (!commentText || !currentMomentId) return;
    
    const content = commentText.value.trim();
    if (!content) {
        showError('Comment cannot be empty');
        return;
    }
    
    if (!window.wsManager || !window.wsManager.isMomentConnected) {
        showError('Not connected to server');
        return;
    }
    
    // Send comment via WebSocket
    window.wsManager.commentOnMoment(currentMomentId, content);
}

// Confirm deletion of a moment
function confirmDeleteMoment(momentId) {
    if (confirm('Are you sure you want to delete this moment?')) {
        deleteMoment(momentId);
    }
}

// Delete a moment
function deleteMoment(momentId) {
    if (!window.wsManager || !window.wsManager.isMomentConnected) {
        showError('Not connected to server');
        return;
    }
    
    // Send delete request via WebSocket
    window.wsManager.deleteMoment(momentId);
}

// Confirm deletion of a comment
function confirmDeleteComment(commentId) {
    if (confirm('Are you sure you want to delete this comment?')) {
        deleteComment(commentId);
    }
}

// Delete a comment
function deleteComment(commentId) {
    if (!window.wsManager || !window.wsManager.isMomentConnected) {
        showError('Not connected to server');
        return;
    }
    
    // Send delete request via WebSocket
    window.wsManager.deleteComment(commentId);
    }
    
// Open the post modal
function openPostModal() {
    if (!postModal) return;
        
    // Clear previous content and preview
    postContent.value = '';
        mediaPreview.innerHTML = '';
    pendingMediaUploads = [];
    
    // Reset checkbox
    if (postTop) postTop.checked = false;
    
    // Show the modal
    postModal.style.display = 'flex';
    
    // Focus on the content textarea
    postContent.focus();
}

// Close the post modal
function closePostModal() {
    if (!postModal) return;
    
    postModal.style.display = 'none';
}

// Handle image upload
function handleImageUpload(event) {
    const files = event.target.files;
    if (!files || files.length === 0) return;
        
    // Process each file
    Array.from(files).forEach(file => {
        // Check if the file is an image
        if (!file.type.startsWith('image/')) {
            showError('Please upload only image files');
            return;
        }
        
        // Check file size (limit to 5MB)
        if (file.size > 5 * 1024 * 1024) {
            showError('Image is too large. Maximum size is 5MB.');
            return;
        }
        
        // Upload the file
        uploadMedia(file);
        });
        
    // Reset the input to allow selecting the same file again
    event.target.value = '';
}

// Handle video upload
function handleVideoUpload(event) {
    const file = event.target.files[0];
    if (!file) return;
        
    // Check if the file is a video
    if (!file.type.startsWith('video/')) {
        showError('Please upload only video files');
        return;
    }
    
    // Check file size (limit to 20MB)
    if (file.size > 20 * 1024 * 1024) {
        showError('Video is too large. Maximum size is 20MB.');
            return;
        }
        
    // Upload the file
    uploadMedia(file);
    
    // Reset the input to allow selecting the same file again
    event.target.value = '';
}

// Upload media file
function uploadMedia(file) {
    if (!window.wsManager || !window.wsManager.isMomentConnected) {
        showError('Not connected to server');
        return;
    }
    
    // Create a loading preview
    const tempPreviewId = 'temp_' + Date.now();
    const previewItem = document.createElement('div');
    previewItem.className = 'preview-item loading';
    previewItem.id = tempPreviewId;
    
    if (file.type.startsWith('image/')) {
        previewItem.innerHTML = `<i class="fas fa-spinner fa-spin"></i><span>Uploading image...</span>`;
    } else {
        previewItem.innerHTML = `<i class="fas fa-spinner fa-spin"></i><span>Uploading video...</span>`;
    }
    
    mediaPreview.appendChild(previewItem);
        
    // Upload the file via WebSocket
    window.wsManager.uploadMomentMedia(file)
        .catch(error => {
            console.error('Failed to upload media:', error);
            previewItem.className = 'preview-item error';
            previewItem.innerHTML = `<i class="fas fa-exclamation-circle"></i><span>Failed to upload</span>`;
            setTimeout(() => previewItem.remove(), 3000);
        });
    }
    
// Add media to preview
function addMediaToPreview(url) {
    // Remove any loading previews
    const loadingPreviews = mediaPreview.querySelectorAll('.preview-item.loading');
    loadingPreviews.forEach(item => item.remove());
    
    // Create a new preview item
    const previewItem = document.createElement('div');
    previewItem.className = 'preview-item';
    
    // Determine if it's an image or video based on the URL
    if (url.match(/\.(jpeg|jpg|gif|png)$/i)) {
        previewItem.innerHTML = `
            <img src="${url}" alt="Preview">
            <button class="remove-media-btn" data-url="${url}">
                <i class="fas fa-times"></i>
            </button>
        `;
    } else if (url.match(/\.(mp4|webm|ogg)$/i)) {
        previewItem.innerHTML = `
            <video src="${url}" controls></video>
            <button class="remove-media-btn" data-url="${url}">
                <i class="fas fa-times"></i>
            </button>
        `;
        } else {
        previewItem.innerHTML = `
            <div class="file-preview">
                <i class="fas fa-file"></i>
                <span>File</span>
            </div>
            <button class="remove-media-btn" data-url="${url}">
                <i class="fas fa-times"></i>
            </button>
        `;
        }
        
    // Add event listener to remove button
    const removeBtn = previewItem.querySelector('.remove-media-btn');
    if (removeBtn) {
        removeBtn.addEventListener('click', function() {
            const url = this.dataset.url;
            removeMediaFromPending(url);
            previewItem.remove();
        });
    }
    
    mediaPreview.appendChild(previewItem);
}

// Remove media from pending uploads
function removeMediaFromPending(url) {
    const index = pendingMediaUploads.indexOf(url);
    if (index !== -1) {
        pendingMediaUploads.splice(index, 1);
    }
}

// Publish a new moment
function publishPost() {
    const content = postContent.value.trim();
        
    if (!content && pendingMediaUploads.length === 0) {
        showError('Please add some content or media to your post');
        return;
    }
    
    if (!window.wsManager || !window.wsManager.isMomentConnected) {
        showError('Not connected to server');
        return;
    }
    
    // Finalize media uploads first
    if (pendingMediaUploads.length > 0) {
        window.wsManager.finalizeMomentMediaUploads()
            .then(() => {
                // Then send the moment
                sendMoment(content);
            })
            .catch(error => {
                console.error('Failed to finalize media uploads:', error);
                showError('Failed to upload media');
            });
    } else {
        // No media, just send the moment
        sendMoment(content);
        }
    }
    
// Send a new moment
function sendMoment(content) {
    const visibility = postTop && postTop.checked ? 'PUBLIC' : 'FRIENDS';
    
    // Send moment via WebSocket
    window.wsManager.sendMoment(content, pendingMediaUploads, visibility);
}

// Handle scroll for infinite loading
function handleScroll(event) {
    const container = event.target;
    const scrollHeight = container.scrollHeight;
    const scrollTop = container.scrollTop;
    const clientHeight = container.clientHeight;
    
    // If we're near the bottom and there are more pages
    if (scrollTop + clientHeight >= scrollHeight - 100 && currentPage < totalPages - 1 && !loading) {
        // Load next page
        loadMoments(currentPage + 1);
    }
    }
    
// Show loading spinner
function showLoading() {
    if (!socialFeed) return;
    
    // Add loading indicator if it doesn't exist
    if (!document.querySelector('.loading-indicator')) {
        const loadingIndicator = document.createElement('div');
        loadingIndicator.className = 'loading-indicator';
        loadingIndicator.innerHTML = `
            <i class="fas fa-spinner fa-spin"></i>
            <span>Loading moments...</span>
        `;
        socialFeed.appendChild(loadingIndicator);
    }
}

// Hide loading spinner
function hideLoading() {
    loading = false;
    const loadingIndicator = document.querySelector('.loading-indicator');
    if (loadingIndicator) {
        loadingIndicator.remove();
    }
}

// Show error message
function showError(message) {
    const errorToast = document.createElement('div');
    errorToast.className = 'error-toast';
    errorToast.textContent = message;
    document.body.appendChild(errorToast);
    
    // Remove after 3 seconds
        setTimeout(() => {
        errorToast.remove();
    }, 3000);
    }
    
// Format moment date
function formatMomentDate(date) {
        const now = new Date();
    const diffInSeconds = Math.floor((now - date) / 1000);
    
    if (diffInSeconds < 60) {
        return 'Just now';
    } else if (diffInSeconds < 3600) {
        const minutes = Math.floor(diffInSeconds / 60);
        return `${minutes} ${minutes === 1 ? 'minute' : 'minutes'} ago`;
    } else if (diffInSeconds < 86400) {
        const hours = Math.floor(diffInSeconds / 3600);
        return `${hours} ${hours === 1 ? 'hour' : 'hours'} ago`;
    } else if (diffInSeconds < 604800) {
        const days = Math.floor(diffInSeconds / 86400);
        return `${days} ${days === 1 ? 'day' : 'days'} ago`;
    } else {
        return date.toLocaleDateString();
    }
}

// Format moment content
function formatMomentContent(content) {
    if (!content) return '';
    
    // Escape HTML
    let formatted = escapeHtml(content);
    
    // Convert URLs to links
    formatted = formatted.replace(
        /(https?:\/\/[^\s]+)/g, 
        '<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>'
    );
    
    // Convert line breaks to <br>
    formatted = formatted.replace(/\n/g, '<br>');
    
    return formatted;
    }
    
// Helper function to escape HTML
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
} 